
import { useRoute } from 'vue-router';
import { useUserApi } from '@/api/user';
import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import { AuthUtils } from '/@/utils';


export const useMenuStore = defineStore('Menu', {
	state: () => ({
		// 路由数据
		route: [],
		// 是否开启加密
		addRoutes: [],
		// 动态添加菜单路由
		addRoutesMap: {},
		// 添加菜单路由参数
		routeParamsMap: {},
	}),
	actions: {
		getUserMenus() {
			return new Promise((resolve, reject) => {
				useUserApi()
					.getUserMenus()
					.then((res) => {
						const { code, data, msg } = res;
						let result = []
						if (code === 200 && data instanceof Object) {
							result = data.router
							.filter(item => [
								'/system-new'
							].includes(item.path))
							result = this.parseAsyncRoutes(result);
							// console.log('getUserMenus', result)
							if (result.length <= 0) {
								ElMessage.warning('抱歉，您没有登录权限，请联系管理员！');
							}
						}
						resolve(result);
					});
			});
		},
		getRouteParams() {
			const route = useRoute();
			return this.routeParamsMap[route.path];
		},
		parseAsyncRoutes(routerMap, parentRoute) {
			if (!routerMap) return []
			return routerMap.map((route) => {
				const { meta, children } = route;
				// 处理菜单图标
				const newMeta = {
					title: meta.title,
					isLink: meta.link,
					isHide: meta.invisible,
					isKeepAlive: true,
					isAffix: false,
					isIframe: false,
					icon: meta.icon,
					roles: ['admin'],
					authority: meta.authority,
					routerParams: meta.routerParams || '',
				};
				let finalIframeSrc = meta.iframeSrc
				if (finalIframeSrc) {
					if (AuthUtils.accessToken.check()) {
						let itoken = AuthUtils.accessToken.get()
						if (finalIframeSrc.includes('?')) {
							finalIframeSrc = `${finalIframeSrc}&itoken=${btoa(itoken)}`
						} else {
							finalIframeSrc = `${finalIframeSrc}?itoken=${btoa(itoken)}`
						}
					}
					newMeta['isLink'] = finalIframeSrc;
					newMeta['isIframe'] = true;
				}
				let newPath = '';
				if (parentRoute) {
					newPath = `${parentRoute.path}/${route.path}`;
				} else {
					newPath = route.path;
				}
				let component = route.component;
				if (['LayoutView', 'BlankView'].includes(route.component)) {
					component = 'layout/routerView/parent';
				} else if(['LayoutLinkView'].includes(route.component)) {
					component = 'layout/routerView/link';
				} else {
					component = component.slice(1);
				}
				// const routerName = component.split('/').slice(-1)[0];
				const routerName = route.name
				const newRoute = {
					path: newPath,
					name: routerName,
					redirect: route.redirect,
					component: component,
					meta: newMeta,
				};
				if (meta.routerParams) {
					let query = {};
					let paramsArray = meta.routerParams.split('&');
					paramsArray.forEach((param) => {
						let paramValues = param.split('=');
						query[paramValues[0]] = paramValues[1];
					});
					newRoute['query'] = query;
					this.routeParamsMap[newPath] = query;
				}
				this.addRoutesMap[newRoute.name] = newRoute;
				if (children && children != null && children.length) {
					const newChildren = this.parseAsyncRoutes(children, newRoute);
					newRoute['children'] = newChildren;
					const firstChildren = newChildren[0];
					if (firstChildren.meta.routerParams) {
						newRoute['redirect'] = `${newChildren[0].path}?${firstChildren.meta.routerParams}`;
					} else {
						newRoute['redirect'] = newChildren[0].path;
					}
				}
				return newRoute;
			});
		},
	},
});
